<?php

/**
 * IndexController - The default controller class
 *
 * @author
 * @version
 */

require_once 'Zend/Controller/Action.php';

class Administrator_ProductController extends Zend_Controller_Action
{



    public function init()
    {

        $member=new CMember();

        if(!$member->isUser($this->_request->getModuleName(),$this->_request->getControllerName()))
        {

            $this->_redirect(MY_URL.'/administrator-auth-login');

        }
        
        $memberArray = $member->getUserDetails(array('uid' => $_COOKIE[COOKIE_PRE.'uid']));
    	if($_COOKIE[COOKIE_PRE.'uid']=='1'){
				
		} else {
        	$strarray = explode(",", $memberArray[0]['menuflag']);
        	
        	if (!in_array('2', $strarray)) {
        		exit('no priviage');
        	}
		}
    }

    public function preDispatch()
    {

        $this->getHelper ('layout')->setLayout('framelayout');

        $this->view->addHelperPath(MY_ROOT.'/vhelpers');

        Zend_Controller_Action_HelperBroker::addPath(MY_ROOT.'/chelpers');

    //$this->getHelper('User')->getinfo($this->view,$this->_request->getModuleName(),$this->_request->getControllerName());

    }

    public function confirmcodeAction()
    {

        $this->getHelper ('layout')->disableLayout ();

        $this->_helper->viewRenderer->setNoRender();

        $this->view->confirmCode('administratorConfirmCode');

    }


    public function indexAction()
    {

        $productfl=new CFenlei('product');

        $fenleiArray=$productfl->getAllFenlei();

        $productfl->getAll($fenleiArray,0);

        $fenleiString=str_replace(array('<div class="smallChildDiv"></div>','<div></div>'),array('',''),$productfl->fenleiString);

        $this->view->assign('fenleiString',$fenleiString);

        Zend_Session::start();

        $sessionPage=new Zend_Session_Namespace('productPage');

        if($sessionPage->page=='')
        {

            $sessionPage->page='1';

        }

        $sessionflid=new Zend_Session_Namespace('productflid');

        if($sessionflid->flid=='')
        {

            $sessionflid->flid='0';

        }

        $this->view->assign('page',$sessionPage->page);

        $this->view->assign('flid',$sessionflid->flid);

    //$myArray=array('a'=>'1','b'=>'2','c'=>'3',array(a1,b1,c1,d1));

    //echo json_encode($myArray);

    }


    public function getitemajaxAction()
    {

        $this->getHelper ('layout')->disableLayout ();

        $flid=$this->_request->getParam('flid');

        $searchQuery=$this->_request->getParam('searchQuery','');
        
        $onsale = $this->_request->getParam('onsale','');

        $page=$this->_request->getParam('page',1);

        Zend_Session::start();

        $sessionPage=new Zend_Session_Namespace('productPage');

        $sessionPage->page=$page;

        $productflid=new Zend_Session_Namespace('productflid');

        $productflid->flid=$flid;


        $searchArray=json_decode(stripslashes($searchQuery),true);

        $where=array();

        if($searchArray['time_from']!='')
        {

            $searchArray['time_from']=strtotime($searchArray['time_from']);

            $where[]="add_time>'".$searchArray['time_from']."'";

        }

        if($searchArray['time_to']!='')
        {

            $searchArray['time_to']=strtotime($searchArray['time_to']);

            $where[]="add_time<'".$searchArray['time_to']."'";

        }


        if($searchArray['seller']!='')
        {

            $member=new CMember();

            $userArray=$member->getUserDetails(array('username'=>$searchArray['seller']));

            $where[]=R_PRE."items.uid='".$userArray[0]['uid']."'";

        }

        if($searchArray['min_price']!='')
        {

            $where[]="min_price>='".$searchArray['min_price']."'";

        }

        if($searchArray['max_price']!='')
        {

            $where[]="max_price<='".$searchArray['max_price']."'";

        }

        if($searchArray['type']!='')
        {
			if (is_numeric($searchArray['type'])) {
            	$where[]="type='".$searchArray['type']."'";
			} else {
				if ($searchArray['type'] == 'isTop') {
					$where[]=R_PRE . "product_attr.attr_name='".$searchArray['type']."' and " . R_PRE . "product_attr.attr_value = 1";
				}
			}
        }

        if($searchArray['keyword']!='')
        {

            $where[]="subject LIKE '%".$searchArray['keyword']."%'";

        }

        $isshow=$this->_request->getParam('isshow');

        //echo $where;

        $item=new CItem();
		
        if ($onsale == 1) {
        	$where[] = R_PRE."products.onsales=1";
        	$isshow = ''; //全部onsale
        }
        		
        if($isshow=='')
        {

            $where=join(' AND ',$where);

            $itemCounts=$item->getAllItemCounts('product',$flid,0,'has_banned',$where);

        }else
        {

            $where[]=R_PRE."products.is_showed='$isshow'";

            $where=join(' AND ',$where);

            $itemCounts=$item->getAllItemCounts('product',$flid,0,'has_banned',$where);

        }
		
        Zend_Loader::loadClass("CFilter");

        $pageArray = CFilter::filterPage ( $page, $itemCounts, 10 );

        $itemArray=$item->getAllItems($pageArray['from'],10,'product',$flid,0,'has_banned',$where,'px ASC,add_time DESC');

        Zend_Loader::loadClass("CPage");

        $pageString = CPage::commonDivAjax($pageArray ['pageNumber'], $pageArray ['page'], 'productEffection.showAll',$flid); //生成分页字符串

        $this->view->assign ( "pageString", $pageString );

        $this->view->assign ( "pageArray", $pageArray );

        $this->view->assign('itemArray',$itemArray);
		/*
		$feature=new CFeature();
		
		$featureArray=$feature->getAllFeatures(0,0);
		
		$this->view->assign('featureArray',$featureArray);
    	*/
    }

    public function dofeatureAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $itemidArray=$this->_request->getParam('itemArray');

        $data=array(
            'featureid'=>$this->_request->getParam('featureid')
        );

        $product=new CProduct();

        foreach($itemidArray as $itemid)
        {

            $product->editProduct($itemid,$data);

        }

        $this->view->showMsg("设置成功!",'administrator'.CHOSING_DE.'product'.CHOSING_DE.'index');

    }

    public function addAction()
    {

        $product=new CFenlei('product');

        $fenleiArray=$product->getFenleiByPid(0);

        $this->view->assign('fenleiArray',$fenleiArray);

        $Csponsors=new Csponsors();
        
        $sponsorsArray=$Csponsors->getAllsponsors();

        $this->view->assign('sponsorsArray',$sponsorsArray);

        $Cbrandlogo=new Cbrandlogo();

        $brandlogoArray=$Cbrandlogo->getAllbrandlogo();

        $this->view->assign('brandlogoArray',$brandlogoArray);

        require_once (MY_ROOT."/fckeditor/fckeditor.php");

        $oFCKeditor = new FCKeditor('FCKeditor1') ;

        $oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;

        $oFCKeditor->Value		= '&nbsp';

        $oFCKeditor->Height=400;

        $oFCKeditor->Width="98%";

        $this->view->assign('oFCKeditor',$oFCKeditor);

        $location=new CFenlei('location');

        $locationArray=$location->getFenleiByPid(0);

        $this->view->assign('locationArray',$locationArray);
        
        //获取配件
        $item = new CItem();
        $flid= 342;
        $accessoryProductArray=$item->getitemidFlid($flid);
        $this->view->assign('accessoryProductArray',is_array($accessoryProductArray)?$accessoryProductArray:array());
        
        $dadge = new CBadge();
        $badgerow = $dadge->getbadgebuyid();
        $this->view->assign('badges',unserialize($badgerow['badges']));
    }

    public function doaddAction()
    {
        $this->_helper->viewRenderer->setNoRender();

        if(!$this->getRequest()->isPost())
        {

            $this->view->showMsg("发生未知错误!");

            return false;

        }

        $paramArray=$this->_request->getParams();




        $filters = array(
            '*'   => 'StringTrim'
        );

        $validators = array(
        );

        $input = new Zend_Filter_Input($filters, $validators, $paramArray);

        $filterChain = new Zend_Filter();

        $filterChain->addFilter(new CornerFilter());

        $subject=$filterChain->filter($input->subject);

        $pattern_intro=$filterChain->filter($input->pattern_intro);

		/*插入到条目表 start*/
        $item=new CItem();
        $itemData=array(
            'uid'=>$_COOKIE[COOKIE_PRE.'uid'],
            'flid'=>$input->flid,
            'subject'=>$subject,
            'item_type'=>'product',
            'add_time'=>time(),
            'update_time'=>time(),
            'is_banned'=>'0',
        );
        $itemid=$item->createItem($itemData);
        $Caccessory = new CProductaccessory();
        if(is_array($input->interrelated)){
        	$accessorydata['itemid']=$itemid;
        	$accessorydata['flid']=0;
        	foreach($input->interrelated as $v){
        		$arr = explode("%%%", $v);
        		$accessorydata['accessoryid']=$arr[0];
        		$accessorydata['price']=$arr[1];
        		$Caccessory->createProductAccessory($accessorydata);
        	}
        }
		/*插入到条目表 end*/


		/*图片附件 start*/
        $cut_url='';
        if(count($paramArray['imgUrl'])>0)
        {
            $resultArray=$this->addAttachment($input,$itemid);
            $attachmentData=$resultArray[0];
            $cut_url=$resultArray[1];
            $medium_url=$resultArray[2];
            $attachment=new CAttachment();
            $attachment->createAttachments($attachmentData);
        }
		/*图片附件 end*/


        /**描述图片附件**/
        $desData = array();
    	for($i=0;$i<count($input->desUrl);$i++)
        {

            $desData[$i]['attachmentid']=$input->desid[$i];
			$arr = array();
            if($desData[$i]['attachmentid']=='')
            {
                $arr[] = array('attachment_url'=>$input->desUrl[$i], 'itemid'=>$itemid);
        		$attachment->editAttachments($arr);
            }
        }
        /**end**/
        
		/*pattern_size*/
        $pattern_size=array();
        $pattern_size_stock = array();

//        foreach ($input->pattern_size as $value)
//        {
//
//            if(trim($value)!='')
//            {
//
//                $pattern_size[]=$value;
//
//            }
//
//        }

        for ($i = 0; $i < count($input->pattern_size); $i++) {
       		if(trim($input->pattern_size[$i]) != '') {
            	$pattern_size[] = $input->pattern_size[$i];
            	$pattern_size_stock[$input->pattern_size[$i]] = $input->pattern_size_stock[$i];
			}
        }
        
		/*pattern_size*/

		/*插入价格表*/
        $priceArray=array();
        $priceArray=$this->addPrice($input,$itemid);
        sort($priceArray);
		/*插入价格表*/


		/*插入到产品表 start*/
        $product=new CProduct();
        $productData=array(
            'itemid'=>$itemid,
            'pattern_intro'=>$pattern_intro,
            'cut_url'=>$cut_url,
        	'medium_url'=>$medium_url,
            'valid_days'=>$input->valid_days,
            'factoryid'=>0,
            'product_code'=>0,
            'is_single'=>$input->is_single,
            'counts_per_pack'=>$input->counts_per_pack=$input->counts_per_pack==''?'0':$input->counts_per_pack,
            'unit'=>$input->unit,
            'size'=>$input->size1.','.$input->size2.','.$input->size3,
            'weight'=>$input->weight,
            'service'=>'',
            'content'=>htmlspecialchars_decode($input->FCKeditor1),
            'state'=>'0',
            'is_showed'=>'1',
            'location_id'=>$input->location_id,
            'min_price'=>$priceArray[0],
        	'm_org_price'=>$priceArray[count($priceArray)-1] + 40,
            'max_price'=>array_pop($priceArray),
            'keywords'=>trim($_POST[keywords]),
            'description'=>trim($_POST[description]),
            'product_sponsors'=>$input->product_sponsors,
            'product_brandlogo'=>$input->product_brandlogo,
            'product_teambadge'=>$input->product_teambadge,
            'product_pattern'=>serialize($pattern_size),
        	'product_pattern_stock'=>serialize($pattern_size_stock),
        	'slug'=>$input->slug
        	//'select_badgepatch_p'=>(isset($input->select_badgepatch_p) && is_array($input->select_badgepatch_p)) ? serialize($input->select_badgepatch_p) : '',
        );
    
        $product->createProduct($productData);
        
        CCache::flushCombinlistItemMap();
        
		/*插入到产品表 end*/
		//$product->copytosite($itemid,'goaljerseys');
        $this->view->showMsg("发表成功!",'administrator-product-index');

        return true;

    }


    public function addAttachment($input,$itemid)
    {

        $attachmentData=array();

        $path=new CPath();

        //$image=new CImage();

        $img=new CClsImage();

        Zend_Loader::loadClass('CFile');

        $cut_url='';

        for($i=0;$i<count($input->imgUrl);$i++)
        {
            $newPath=$path->toDbPath('item',$input->imgUrl[$i]);//生成新的item图片路径
            CFile::copyAndUnlink($path->toAbsoluteRootPath($input->imgUrl[$i]),$path->toAbsoluteRootPath($newPath));//从临时文件夹转到item图片文件夹

            //$cutPath=$image->cutPhoto($newPath, '250', $path->getPathFromType('cut_item'));//截图

            $paramArray=$this->_request->getParams();

            $paramArray=$this->_request->getParams();
            if($paramArray["thumbcaek"])
            {
                $cutPath=$img->make_thumb($newPath,165,0,$path->getPathFromType('cut_item'));
            }else
            {
                $cutPath=$img->make_thumb($newPath,165,0,$path->getPathFromType('cut_item'));
                //$cutPath=$img->make_thumb($newPath,200,200,$path->getPathFromType('cut_item'));
                //$cutPath= str_replace("/item_img/","/cut_item_img/",$newPath)  ;
                //die(realpath( './' )."/".$newPath);
                //copy(realpath( './' )."/".$newPath,realpath( './' )."/".$cutPath);
            }
            
            $attachmentData[$i]['itemid']=$itemid;

            $attachmentData[$i]['attachment_url']=$newPath;

            $attachmentData[$i]['cut_url']=$path->toDbPath('cut_item',$cutPath);

            $attachmentData[$i]['intro']=$input->imgIntro[$i];

            if($input->imgUrl[$i]==$input->cut_url)
            {

                $cut_url=$attachmentData[$i]['cut_url'];
				$toPath = str_replace('item_img', 'medium_img', $attachmentData[$i]['attachment_url']);
        		$toPathArr = pathinfo($toPath);
        		$filename = $img->make_thumb2(MY_ROOT . "/" .$attachmentData[$i]['attachment_url'],260,260,MY_ROOT . "/" . $toPathArr['dirname'] . '/', '', $toPathArr['filename']);
            	$medium_url = $toPathArr['dirname'] . '/' . $toPathArr['filename'] . '.jpg';
            }

        }
		//小缩略图
        $toPath = str_replace('cut_item_img', 'new_cut_item_img', $cut_url);
        $toPathArr = pathinfo($toPath);
        $filename = $img->make_thumb2(MY_ROOT . "/" .$cut_url,122,0,MY_ROOT . "/" . $toPathArr['dirname'] . '/', '', $toPathArr['filename']);
        return array($attachmentData,$cut_url, $medium_url);

    }
  
    public function addPrice($input,$itemid)
    {

        $productPrice=new CProductPrice();

        $patternArray=$input->pattern_name;

        $priceArray=array();

        for($i=0;$i<count($patternArray);$i++)
        {

            $data=array(
                'itemid'=>$itemid,
                'min_counts'=>$input->min_counts[$i],
                'max_counts'=>$input->max_counts[$i],
                'supply_price'=>$input->supply_price[$i],
                'net_price'=>round($input->supply_price[$i]*SELL_RATE,2),
                'delivery_days'=>$input->delivery_days[$i],
                'pattern_name'=>$input->pattern_name[$i],
            );

            $priceArray[]=round($input->supply_price[$i]*SELL_RATE,2);

            $productPrice->createPrice($data);
        }

        return $priceArray;

    }

    public function editAction()
    {

        $product=new CFenlei('product');

        $itemid=$this->_request->getParam('itemid');

        $fenleiArray=$product->getFenleiByPid(0);

        $this->view->assign('fenleiArray',$fenleiArray);

        $Csponsors=new Csponsors();

        $sponsorsArray=$Csponsors->getAllsponsors();

        $this->view->assign('sponsorsArray',$sponsorsArray);

        $Cbrandlogo=new Cbrandlogo();

        $brandlogoArray=$Cbrandlogo->getAllbrandlogo();

        $this->view->assign('brandlogoArray',$brandlogoArray);

        $item=new CItem();

        $itemArray=$item->getDetail($itemid,'product');

        $this->view->assign('itemArray',$itemArray);
        //获取配件信息
        $accessory = new CProductaccessory();
        $info = $accessory->getProductAccessory($itemid);
        $this->view->assign('info',is_array($info)?$info:array());
        
        $flid=342;
        $bindProductArray=$item->getitemidFlid($flid);
        foreach($info as $k=>$v){
        	foreach($bindProductArray as $key=>$value){
        		if($v[accessoryid]==$value['itemid']){
        			unset($bindProductArray[$key]);
        		}
        	}
        }
        $this->view->assign('bindProductArray',is_array($bindProductArray)?$bindProductArray:array());

        $pattern_size=unserialize($itemArray[0]['product_pattern']);
        $pattern_size_stock = unserialize($itemArray[0]['product_pattern_stock']);

        $this->view->pattern_size_stock = is_array($pattern_size_stock) ? $pattern_size_stock : array();
        $this->view->assign('pattern_size',is_array($pattern_size)?$pattern_size:array());

        $select_Original=unserialize($itemArray[0]['select_Original']);

        $this->view->assign('select_Original',is_array($select_Original)?$select_Original:array());

        $sizeArray=explode(',',$itemArray[0]['size']);

        $this->view->assign('sizeArray',$sizeArray);

        $product=new CFenlei('product');

        $productflArray=$product->getAllFenlei();

        $selectString=$product->getAllSelect($productflArray,$itemArray[0]['flid'],'fenleiEffection.getChildFenlei(this);');

        $this->view->assign('selectString',$selectString);

        $attachment=new CAttachment();

        $attachmentArray=$attachment->getAttachments($itemid, 'cut_url != ""');

        $this->view->assign('attachmentArray',$attachmentArray);
        
        $desImgArr=$attachment->getAttachments($itemid, 'cut_url = ""');
        $this->view->assign('desImgArr',$desImgArr);

        $productPrice=new CProductPrice();

        $priceArray=$productPrice->getAllPrice($itemid);

        $this->view->assign('priceArray',$priceArray);

        $productFl=new CFenlei('product');

        $flArray=$this->getHelper('Fenlei')->getFenleiChild($productFl->getFenleiTree(),$item->getitemfuid($itemArray[0]['flid'].""));

        $selectinterrelatedArray=$item->getitemidFlid(join(',',$flArray)."");
   
        $this->view->assign('selectinterrelatedArray',$selectinterrelatedArray);

        $interrelatedArray=$item->getitemidIN($itemArray[0]['interrelated']);

        $this->view->assign('interrelatedArray',$interrelatedArray);

        require_once (MY_ROOT."/fckeditor/fckeditor.php");

        $oFCKeditor = new FCKeditor('FCKeditor1') ;

        $oFCKeditor->BasePath	= ROOT_PATH.'/fckeditor/' ;

        $oFCKeditor->Value		= $itemArray[0]['content'];

        $oFCKeditor->Height=400;

        $oFCKeditor->Width="98%";

        $this->view->assign('oFCKeditor',$oFCKeditor);

        $location=new CFenlei('location');

        $location->setSelectid('locationSelect');

        $locationArray=$location->getAllFenlei();

        $locationSelectString=$location->getAllSelect($locationArray,$itemArray[0]['location_id'],'locationFl.getChildFenlei(this);');
        $this->view->assign('locationSelectString',$locationSelectString);
        /**
        $dadge = new CBadge();
        $badgerow = $dadge->getbadgebuyid();
        $this->view->assign('badges',unserialize($badgerow['badges']));
        */
        $badge = new CBadge();
        $badgeRow = $badge->fetchAll();
        $this->view->badges = $badgeRow;
        $selectBadge = $badge->getItemBadge($itemid);
        $selectBadgeId = array();
        foreach ($selectBadge as $v) {
        	$selectBadgeId[] = $v['badge_id'];
        }
        $this->view->selectBadgeId = $selectBadgeId;
    }

    public function doeditAction()
    {
        $this->_helper->viewRenderer->setNoRender();

        if(!$this->getRequest()->isPost())
        {

            $this->view->showMsg("发生未知错误!");

            return false;

        }

        $paramArray=$this->_request->getParams();

        $itemid=$paramArray['itemid'];
		/*
		Zend_Session::start();
		
    	if(strtolower($paramArray['productyz'])!=strtolower($_SESSION['adminsProductConfirmCode'])){
			
			$this->view->showMsg("验证码错误!");
			
			return false;
			
		}*/


        $filters = array(
            '*'   => 'StringTrim'
        );

        $validators = array(
        );

        $input = new Zend_Filter_Input($filters, $validators, $paramArray);

      //  $select = new Zend_Filter_Input($filters, $validators, $paramArray);

        $filterChain = new Zend_Filter();

        $filterChain->addFilter(new CornerFilter());

        $subject=$filterChain->filter($input->subject);

        $pattern_intro=$filterChain->filter($input->pattern_intro);

        if($_POST[interrelated])
        {
        $interrelated = join(",",$_POST[interrelated]);
        }

		/*插入到条目表 start*/
        $item=new CItem();
        $itemData=array(
            'flid'=>$input->flid,
            'subject'=>$subject,
            'interrelated'=>$interrelated,
            'add_time'=>strtotime($input->add_time),
            'px'=>$input->px,
            'update_time'=>time(),
        );
        $item->editItem($itemid,$itemData);
        
        $accessory = new CProductaccessory();
        $accessory->delProductAccessory($itemid);
        if(is_array($input->bind2)){
        	$accessorydata['itemid']=$itemid;
        	$accessorydata['flid']=0;
        	foreach($input->bind2 as $v){
        		$arr = explode("%%%", $v);
        		$accessorydata['accessoryid']=$arr[0];
        		$accessorydata['price']=$arr[1];
        		$accessory->createProductAccessory($accessorydata);
        	}
        }
		/*插入到条目表 end*/
		/*图片附件 start*/
        $resultArray=$this->editAttachment($input,$itemid);
        $attachmentData=$resultArray[0];
        $cut_url=$resultArray[1];
        $medium_url = $resultArray[2];
        $attachment=new CAttachment();
        $attachment->editAttachments($attachmentData);

		/*图片附件 end*/

        /**描述图片附件**/
        $desData = array();
    	for($i=0;$i<count($input->desUrl);$i++)
        {

            $desData[$i]['attachmentid']=$input->desid[$i];
			$arr = array();
            if($desData[$i]['attachmentid']=='')
            {
                $arr[] = array('attachment_url'=>$input->desUrl[$i], 'itemid'=>$itemid);
        		$attachment->editAttachments($arr);
            }
        }
        /**end**/

		/*插入价格表*/
        $priceArray=array();
        $priceArray=$this->editPrice($input,$itemid);
        sort($priceArray);
		/*插入价格表*/

		/*pattern_size*/
        $pattern_size=array();
        $pattern_size_stock = array();

//        foreach ($input->pattern_size as $value)
//        {
//
//            if(trim($value)!='')
//            {
//
//                $pattern_size[]=$value;
//
//            }
//
//        }

   		for ($i = 0; $i < count($input->pattern_size); $i++) {
       		if(trim($input->pattern_size[$i]) != '') {
            	$pattern_size[] = $input->pattern_size[$i];
            	$pattern_size_stock[$input->pattern_size[$i]] = $input->pattern_size_stock[$i];
			}
        }       

		/*pattern_size*/
		/*select_Original*/
        $select_Original=array();
     if($input->select_Original){
        foreach ($input->select_Original as $value)
        {

            if(trim($value)!='')
            {

                $select_Original[]=$value;

            }

        }
     }
		/*select_Original*/
		/*插入到产品表 start*/
        $product=new CProduct();
        $productData=array(
            'pattern_intro'=>$pattern_intro,
            'cut_url'=>$cut_url,
			'sku'=>$input->sku,
            'valid_days'=>$input->valid_days,
            'factoryid'=>0,
            'product_code'=>0,
            'is_single'=>$input->is_single,
            'counts_per_pack'=>$input->counts_per_pack=$input->counts_per_pack==''?'0':$input->counts_per_pack,
            'unit'=>$input->unit,
            'size'=>$input->size1.','.$input->size2.','.$input->size3,
            'weight'=>$input->weight,
            'service'=>'',
            'content'=>htmlspecialchars_decode($input->FCKeditor1),
            'state'=>'0',
            'location_id'=>$input->location_id,
            'min_price'=>$priceArray[0],
        	'm_org_price'=>$priceArray[count($priceArray)-1] + 40,
            'max_price'=>array_pop($priceArray),
            'product_sponsors'=>$input->product_sponsors,
            'product_brandlogo'=>$input->product_brandlogo,
            'product_teambadge'=>$input->product_teambadge,
//            'probadgepatch'=>trim($_POST[probadgepatch]),
            'proPrintnumber'=>trim($_POST[proPrintnumber]),
            'prooriginalnumber'=>trim($_POST[prooriginalnumber]),
            'proocustomizeriginal'=>trim($_POST[proocustomizeriginal]),
            'keywords'=>trim($_POST[keywords]),
            'description'=>trim($_POST[description]),
            'select_Original'=>serialize($select_Original),
            'product_pattern'=>serialize($pattern_size),
        	'product_pattern_stock'=>serialize($pattern_size_stock),
        	'stock'=>trim($_POST[stock]),
            'slug'=>$input->slug
        	//'select_badgepatch_p'=>(isset($input->select_badgepatch_p) && is_array($input->select_badgepatch_p)) ? serialize($input->select_badgepatch_p) : '',
        );
        if ($medium_url) {
        	$productData['medium_url'] = $medium_url;
        }
        //臂章
        $db = $product->getAdapter();
        $db->query('delete from zcshop_badge_product where itemid = ' . intval($itemid));
        if ($input->select_badgepatch_p) {
        	foreach ($input->select_badgepatch_p as $v) {
        		$db->query('insert into zcshop_badge_product (itemid, badge_id) values(' . intval($itemid) . ', ' . intval($v) . ')');
        	}
        }
        $product->editProduct($itemid,$productData);
		/*插入到产品表 end*/
		$product->edittosite($itemid, 'goaljerseys');	
		
		$productAttr = new CProductattr();
		$attr = new CAttr();
		$category = intval($_POST['attr_category']);
		
		if ($category) {
			$categoryRow = $attr->fetchRow(array('attr_id = ?'=>$category));
			$attrValue = $categoryRow->attr_name;
		} else {
			$attrValue = '';
		}		
		$productAttr->updateAttr(array('itemid'=>$itemid, 'attr_name'=>'category', 'attr_value'=>$attrValue, 'attr_id_ex'=>$category));
		
		$brand = intval($_POST['attr_brand']);
		
		if ($brand) {
			$brandRow = $attr->fetchRow(array('attr_id = ?'=>$brand));
			$attrValue = $brandRow->attr_name;
		} else {
			$attrValue = '';
		}		
		$productAttr->updateAttr(array('itemid'=>$itemid, 'attr_name'=>'brand', 'attr_value'=>$attrValue, 'attr_id_ex'=>$brand));
		
		$player = intval($_POST['attr_player']);
		if ($player) {
			$playerRow = $attr->fetchRow(array('attr_id = ?'=>$player));
			$attrValue = $playerRow->attr_name;
		} else {
			$attrValue = '';
		}		
		$productAttr->updateAttr(array('itemid'=>$itemid, 'attr_name'=>'player', 'attr_value'=>$attrValue, 'attr_id_ex'=>$player));
		
		CCache::flushCombinlistItemMap();
		
		//$product->copyAttr($itemid, 'goaljerseys');
        $this->view->showMsg("修改成功!",'administrator-product-index');

        return true;

    }

    public function editAttachment($input,$itemid)
    {

        $attachmentData=array();

        $path=new CPath();

        //$image=new CImage();

        $img=new CClsImage();

        Zend_Loader::loadClass('CFile');

        $cut_url='';

        $my_cut_url='';
		$medium_url = '';
        for($i=0;$i<count($input->imgUrl);$i++)
        {

            $attachmentData[$i]['attachmentid']=$input->attachmentid[$i];

            if($attachmentData[$i]['attachmentid']=='')
            {

                $newPath=$path->toDbPath('item',$input->imgUrl[$i]);//生成新的item图片路径

                CFile::copyAndUnlink($path->toAbsoluteRootPath($input->imgUrl[$i]),$path->toAbsoluteRootPath($newPath));//从临时文件夹转到item图片文件夹

                //$cutPath=$image->cutPhoto($newPath, '250', $path->getPathFromType('cut_item'));//截图
                $paramArray=$this->_request->getParams();
                if($paramArray["thumbcaek"])
                {
                    $cutPath=$img->make_thumb($newPath,165,0,$path->getPathFromType('cut_item'));
                }else
                {
                    $cutPath=$img->make_thumb($newPath,165,0,$path->getPathFromType('cut_item'));
                   //$cutPath= str_replace("/item_img/","/cut_item_img/",$newPath)  ;
                   //copy(realpath( './' )."/".$newPath,realpath( './' )."/".$cutPath);
                }

                $cut_url=$path->toDbPath('cut_item',$cutPath);

                $attachmentData[$i]['attachment_url']=$newPath;

                $attachmentData[$i]['cut_url']=$cut_url;

                $attachmentData[$i]['itemid']=$itemid;

                if($input->imgUrl[$i]==$input->cut_url)
                {

                    $my_cut_url=$attachmentData[$i]['cut_url'];
					$toPath = str_replace('item_img', 'medium_img',$attachmentData[$i]['attachment_url']);
        			$toPathArr = pathinfo($toPath);
        			$img->make_thumb2(MY_ROOT . "/" .$attachmentData[$i]['attachment_url'],260,260,MY_ROOT . "/" . $toPathArr['dirname'] . '/', '', $toPathArr['filename']);
        			$medium_url = $toPathArr['dirname'] . '/' . $toPathArr['filename'] . '.jpg';
                }

            }else
            {

                $my_cut_url=$input->cut_url;

                $my_cut_url=$my_cut_url==null?'':$my_cut_url;
                $member = new CMember();
                $db = $member->getAdapter();
                $sql = 'select * from zcshop_attachments where cut_url="'.$input->cut_url.'"';
                $result = $db->fetchRow($sql);
                $itemImg = $result['attachment_url'];          
                
                if($itemImg)
                {
	                $toPath = str_replace('item_img', 'medium_img',$itemImg);
	        		$toPathArr = pathinfo($toPath);
	        		$img->make_thumb2(MY_ROOT . "/" .$itemImg,260,260,MY_ROOT . "/" . $toPathArr['dirname'] . '/', '', $toPathArr['filename']);
	        		$medium_url = $toPathArr['dirname'] . '/' . $toPathArr['filename'] . '.jpg';
                }

            }

            $attachmentData[$i]['intro']=$input->imgIntro[$i];



        }
		$toPath = str_replace('cut_item_img', 'new_cut_item_img', $my_cut_url);
        $toPathArr = pathinfo($toPath);
        $img->make_thumb2(MY_ROOT . "/" .$cut_url,122,0,MY_ROOT . "/" . $toPathArr['dirname'] . '/', '', $toPathArr['filename']);
        return array($attachmentData,$my_cut_url, $medium_url);

    }

    public function editPrice($input,$itemid)
    {

        $productPrice=new CProductPrice();

        $patternArray=$input->pattern_name;

        $priceArray=array();

        for($i=0;$i<count($patternArray);$i++)
        {

            $data[]=array(
                'priceid'=>$input->priceid[$i],
                'itemid'=>$itemid,
                'min_counts'=>$input->min_counts[$i],
                'max_counts'=>$input->max_counts[$i],
                'supply_price'=>$input->supply_price[$i],
                'net_price'=>$input->net_price[$i],
                'delivery_days'=>$input->delivery_days[$i],
                'pattern_name'=>$input->pattern_name[$i],
            );

            $priceArray[]=$input->net_price[$i];

        }

        $productPrice->editPrice($data);

        return $priceArray;

    }
    /**
     * 批量编辑产品尺寸
     * @return boolean
     */
    public function editproductsizeAction(){
    	$product_pattern = array();
    	$product_pattern_stock = array();
    	$product = new CProduct();
    	$res = $this->_request->getPost();
    	$itemid = $this->_request->getParam('itemid',0);
    	if(!empty($res['product_pattern'])){
    	 	foreach($res['product_pattern'] as $k=>$v){
    	 		if(trim($v) != '') {
            		$pattern_size[] = $v;
            		$pattern_size_stock[$v] = $res['product_pattern_stock'][$k];
			}
        }
    	}
		$res = $product->editProductSize($itemid,$pattern_size,$pattern_size_stock);
    	if($res===true){
    		$this->view->showMsg('修改成功!');
    	}else{
    		$this->view->showMsg('修改失败!');
    	}
    	exit();
	}

    public function getfenleiajaxAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $this->getHelper ('layout')->disableLayout ();

        $pid=$this->_request->getParam('pid',0);

        $product=new CFenlei('product');

        $fenleiArray=$product->getFenleiByPid($pid);

        echo json_encode($fenleiArray);

    }


    public function getbadgepatchajaxAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $this->getHelper ('layout')->disableLayout ();

        $pid=$this->_request->getParam('pid',0);
        $product=new CFenlei('product');
        $fenleiArray=$product->getoneFenlei($pid);
        $select_badgepatch = ($fenleiArray[0]['select_badgepatch'] != '') ? unserialize($fenleiArray[0]['select_badgepatch']) : '';
        echo ($select_badgepatch != '') ? json_encode($select_badgepatch) : '';

    }

    public function uploadimgAction()
    {

        header("Content-type: text/html; charset=utf-8");

        $this->getHelper ('layout')->disableLayout ();

        $upload=new CUpload();

        $path=new CPath();

        $thisPath=$path->getPathFromType('temp');

        $imageArray=$upload->uploadFile($thisPath,null,null,'500000');

        $isSuccess=false;

        if(is_array($imageArray))
        {

            $isSuccess=true;

            $imgUrl=$path->toDbPath('temp',$imageArray[0]);

            $this->view->assign('imgUrl',$imgUrl);

        }else
        {

            $error=$imageArray;

            $this->view->assign('error',$error);

        }

        $this->view->assign('isSuccess',$isSuccess);

    }
    
public function uploadimgmulAction()
    {
		set_time_limit(0);
        header("Content-type: text/html; charset=utf-8");        

        $this->getHelper ('layout')->disableLayout ();

        $upload=new CUpload();

        $path=new CPath();

        $thisPath=$path->getPathFromType('temp');

        $imageArray=$upload->uploadFile($thisPath,null,null,'500000');    
        

        $isSuccess=false;

        if(is_array($imageArray))
        {

            $isSuccess=true;
            $imgUrl = array();
			foreach ($imageArray as $v) {
				$imgUrl[] = $path->toDbPath('temp',$v);
			}
			$itemid = $this->getRequest()->getParam('itemid');
			$itemid = intval($itemid);			

            $this->view->assign('imgUrl',$imgUrl);

        }else
        {

            $error=$imageArray;

            $this->view->assign('error',$error);

        }

        $this->view->assign('isSuccess',$isSuccess);

    }

    public function dodelAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $itemid=$this->_request->getParam('itemid');

        if($itemid=='')
        {

            $itemidArray=$this->_request->getParam('itemArray');

        }else
        {

            $itemidArray=array($itemid);

        }

        $product=new CProduct();

        $item=new CItem();

        $product->delProducts($itemidArray);

        $item->delItems($itemidArray);

        $attachment=new CAttachment();

        $attachment->delAttachmentsByItemid($itemidArray);

        $price=new CProductPrice();

        $price->delPricesByItemid($itemidArray);
		
        //index
		$index=Zend_Search_Lucene::create(MY_ROOT."/indexdata/index");
	
		$item=new CItem();
		$result = $item->getAllItems(0,0,'product',0,0,'has_banned',$where='zcshop_products.is_showed=1 and zcshop_products.onsales=0 and min_price < max_price');
		$success = 0;
		
		for($i=0;$i<count($result);$i++){//count($result)
			try{
			$doc=new Zend_Search_Lucene_Document();
			$doc->addField(Zend_Search_Lucene_Field::UnIndexed('PID',$result[$i]['itemid']));
			$doc->addField(Zend_Search_Lucene_Field::UnStored('subject',$result[$i]['subject']));
			$doc->addField(Zend_Search_Lucene_Field::UnStored('content',$result[$i]['pattern_intro'] . ' ' . $this->view->toText($result[$i]['content']) . ' ' . $result[$i]['keywords'] . ' ' . $result[$i]['description'],'utf-8'));
			$index->addDocument($doc);
			}catch (Exception $e)
			{
				echo $e->getMessage();exit;
			}
			$success++;
		}
		$index->optimize();
		$index->commit();
		//
        
        $this->view->showMsg('删除成功!');

    }

    public function delimgAction()
    {

        $this->getHelper ('layout')->disableLayout ();

        $this->_helper->viewRenderer->setNoRender();

        if(unlink(MY_ROOT.'/'.$this->_request->getParam('imgurl')))
        {

            echo 'success';

        }else
        {
            echo 'error';
        }

    }

    public function delimgbyidAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $this->getHelper ('layout')->disableLayout ();

        $attachmentid=$this->_request->getParam('attachmentid');

        $is_cut_url=$this->_request->getParam('is_cut_url');//当is_cut_url不为1即表明用户要删除的图片是截图

        $attachment=new CAttachment();

        $attachmentArray=$attachment->getAttachmentByAttachmentid($attachmentid);

        $attachment_url=$attachmentArray['attachment_url'];

        $cut_url=$attachmentArray['cut_url'];

        $itemid=$attachmentArray['itemid'];

        $path=new CPath();

        @unlink($path->toAbsoluteRootPath($attachment_url));

        @unlink($path->toAbsoluteRootPath($cut_url));

        if($is_cut_url!='')
        {

            $product=new CProduct();

            $product->editProduct($itemid,array('cut_url'=>''));

        }

        $attachment->delAttachmentsById(array($attachmentid));

        echo 'success';
    }

    public function delpriceajaxAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $this->getHelper ('layout')->disableLayout ();

        $priceid=$this->_request->getParam('priceid');

        $price=new CProductPrice();

        $price->delPrices(array($priceid));

        echo 'success';

    }

    public function setproducttypeAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $type=$this->_request->getParam('type');

        $itemidArray=$this->_request->getParam('itemArray');

        $item=new CProduct();

        $item->editProducts($itemidArray,array('type'=>$type));

		/*
		switch ($type){
			
			case 'hot':
				$item->editProducts($itemidArray,array('is_hot'=>'1','is_new'=>'0','is_best'=>'0'));
				break;
			case 'new':
				$item->editProducts($itemidArray,array('is_hot'=>'0','is_new'=>'1','is_best'=>'0'));
				break;
			case 'best':
				$item->editProducts($itemidArray,array('is_hot'=>'0','is_new'=>'0','is_best'=>'1'));
				break;
			default:
				$item->editProducts($itemidArray,array('is_hot'=>'0','is_new'=>'0','is_best'=>'0'));
				
		}
		*/

        $this->view->showMsg("设置成功！",$_SERVER['HTTP_REFERER']);



    }

    public function setshowAction()
    {

        $this->_helper->viewRenderer->setNoRender();

        $isshow=$this->_request->getParam('isshow');

        $itemidArray=$this->_request->getParam('itemArray');

        $product=new CProduct();

        if($isshow==1||$isshow==0)
        {

            for($i=0;$i<count($itemidArray);$i++)
            {

                $product->editProduct($itemidArray[$i],array('is_showed'=>$isshow));
                $product->copyIsShow($itemidArray[$i], 'goaljerseys', $isshow);

            }
            //index
			$index=Zend_Search_Lucene::create(MY_ROOT."/indexdata/index");
		
			$item=new CItem();
			$result = $item->getAllItems(0,0,'product',0,0,'has_banned',$where='zcshop_products.is_showed=1 and zcshop_products.onsales=0 and min_price < max_price');
			$success = 0;
			
			for($i=0;$i<count($result);$i++){//count($result)
				try{
				$doc=new Zend_Search_Lucene_Document();
				$doc->addField(Zend_Search_Lucene_Field::UnIndexed('PID',$result[$i]['itemid']));
				$doc->addField(Zend_Search_Lucene_Field::UnStored('subject',$result[$i]['subject']));
				$doc->addField(Zend_Search_Lucene_Field::UnStored('content',$result[$i]['pattern_intro'] . ' ' . $this->view->toText($result[$i]['content']) . ' ' . $result[$i]['keywords'] . ' ' . $result[$i]['description'],'utf-8'));
				$index->addDocument($doc);
				}catch (Exception $e)
				{
					echo $e->getMessage();exit;
				}
				$success++;
			}
			$index->optimize();
			$index->commit();
			//
            $this->view->showMsg('设置成功!');

        }else
        {

            $this->view->showMsg('设置有误!');

        }


    }

    public function postAction()
    {

    //$this->_helper->viewRenderer->setNoRender();

    //$this->getHelper ('layout')->disableLayout ();

    }
    
    public function badgeindexAction()
    {
    	$dadge = new CBadge();
    	$data = $dadge->getbadgebuyid();
    	$arr = unserialize($data['badges']);
    	$this->view->assign('select_badgepatch',$arr);
    	$this->view->assign('id',$data['badge_id']);
    }
    
    public function badgeupdateAction()
    {
    	if($this->getRequest()->isPost()) {
	    	$this->_helper->viewRenderer->setNoRender();
	    	$dadge = new CBadge();
	    	$select_badgepatch = array();
	    	
	    	$paramArray=$this->_request->getParams();
	    	
	    	$filters = array(
            '*'   => 'StringTrim'
	        );
	
	        $validators = array(
	        );

        	$input = new Zend_Filter_Input($filters, $validators, $paramArray);
        	
        	print_r($input);exit();
	        if ($input->select_badgepatch)
	        {
	        	$i = 0;
	            foreach ($input->select_badgepatch as $value)
	            {
	
	                if (trim($value) != '')
	                {
	
	                    $select_badgepatch[] = array('name'=>$value, 'img'=>$input->badge_img[$i]);                    
	                }
	                $i++;
	            }
	        }
	    	if($dadge->update(array('badges'=>serialize($select_badgepatch))))
	    	{
	    		$this->view->showMsg("设置成功！",$_SERVER['HTTP_REFERER']);
	    	}
	    	else
	    	{
	    		$this->view->showMsg("设置失败,请重试！",$_SERVER['HTTP_REFERER']);
	    	}
    	}
    }
    
	public function uploadimg1Action()
    {

        header("Content-type: text/html; charset=utf-8");

        $this->getHelper ('layout')->disableLayout ();

        $upload=new CUpload();

        $path=new CPath();

        $thisPath=$path->getPathFromType('temp');

        $imageArray=$upload->uploadFile($thisPath,null,null,'500000');

        $isSuccess=false;

        if(is_array($imageArray))
        {

            $isSuccess=true;

            $imgUrl=$path->toDbPath('temp',$imageArray[0]);

            $this->view->assign('imgUrl',$imgUrl);

        }else
        {

            $error=$imageArray;

            $this->view->assign('error',$error);

        }

        $this->view->assign('isSuccess',$isSuccess);

    }
    
    public function commentAction()
    {
    	$page=$this->_request->getParam('page');
		$productReview = new CProductreview();	
		$itemId = $this->getRequest()->getParam('itemid');
		$pageCount = $productReview->getPageCount($itemId,1);
		
		if ($page <= 0 ) {
			$page = 1;
		}
		
		$member = new CMember();
    	Zend_Loader::loadClass("CFilter");
    	$pageArray = CFilter::filterPage ( $page, $pageCount, 5 );
		$itemArray = $productReview->fetchReview($page, 5, $itemId);
		Zend_Loader::loadClass("CPage");
    	$pageString = CPage::divPages( $pageArray ['pageNumber'], $pageArray ['page'], ROOT_PATH."/administrator-product-comment?itemid=" . $itemId); //生成分页字符串
    	$this->view->assign ( "pageString", $pageString );
    	$this->view->assign ( "pageArray", $pageArray );
		$this->view->assign('comment',$itemArray);
		$this->view->member = $member;
    }
    
    public function addcommentAction()
    {
    	$itemId = $this->getRequest()->getParam('itemid');
    	$this->view->itemid = $itemId;
    	if ($this->getRequest()->isPost()) {
    		$productScore = $this->getRequest()->getParam('product_score');
    		$shipScore = $this->getRequest()->getParam('ship_score');
    		$overallScore = $this->getRequest()->getParam('overall_score');
    		$comment = $this->getRequest()->getParam('comment');
    		$comment = $this->view->escape($comment);
    		$orderId = 0;
    		
    		$nickName = $this->getRequest()->getParam('nickname');
    		
    		$buyer = new CBuyer();
    		
    		$user = $buyer->getUserDetails(array('nick_name'=>$nickName));
    		
    		if (empty($user)) {  
    			$buyer = new CBuyer();  		
    			$commonData = array('username'=>'',
					                'userpass'=>'no',
					        	    'passwd'=>'no',
					                'email'=>'no',
					        	    'clubid'=>0,
					        	    'subscribe'=>1,
					                'reg_time'=>time(),
					                'reg_ip'=>'127.0.0.1',
					                'member_type'=>'buyer',
					                'email_code'=>'1',
					                'is_enterprice'=>'0'        		
					        	  );
				$buyerData=array('nick_name'=>$nickName,
				                 'btypeid'=>1
				        		 );        
        		$uid = $buyer->create($commonData,$buyerData);
    		} else {
    			$uid = $user[0]['uid'];
    		}
    		
    		$row = array('itemid'=>$itemId, 'orderid'=>$orderId, 'uid'=>$uid,
    					 'product_score'=>$productScore, 'ship_score'=>$shipScore, 'overall_score'=>$overallScore, 'comments'=>$comment, 'add_time'=>time());
    		
    		$productReview = new CProductreview();
    		
    		if ($productReview->add($row)) {
    			$this->getHelper('viewRenderer')->setNoRender();
    			$this->view->showMsg('添加成功', '/administrator-product-addcomment?itemid=' . $itemId);
    		}
    	}
    }
    
	public function deletecommentAction()
	{
		$this->_helper->viewRenderer->setNoRender();
    	$itemid = $this->_request->getParam('itemid');
    	if ($itemid == '') {
    		$itemidArray = $this->_request->getParam('itemArray');
    	} else {    		
    		$itemidArray=array($itemid);    		
    	}
    	$productReview = new CProductreview();    	
    	$productReview->delete($itemidArray);    	
    	$this->view->showMsg('删除成功!');
	}
	
	public function copyAction()
	{
		$this->_helper->viewRenderer->setNoRender();
    	$itemid = $this->_request->getParam('itemid');
    	if ($itemid == '') {
    		$this->view->showMsg("错误的参数！",$_SERVER['HTTP_REFERER']);
    	} else {    		
    		$product = new CProduct();
    		$newitemid = $product->copy($itemid);
    		if($newitemid > 0)
    		{
    			$product->copytosite($newitemid, 'goaljerseys');
    			$this->view->showMsg("复制成功,请对该产品信息进行再次编辑！",'/administrator-product-edit?itemid=' .$newitemid);
    		} else {
    			$this->view->showMsg("复制失败！",'/administrator-product');
    		}
    	}
	}
	
	public function setattrAction()
    {

        $this->_helper->viewRenderer->setNoRender();
        $type = $this->_request->getParam('type');
        $value = $this->getRequest()->getParam('value');
		$attrArr = array('isTop');
        $itemidArray=$this->_request->getParam('itemArray');

        $productAttr = new CProductattr();
        $product = new CProduct();
        if(in_array($type, $attrArr))
        {

            for($i=0;$i<count($itemidArray);$i++)
            {
				$productAttr->updateAttr(array('itemid'=>$itemidArray[$i], 'attr_name'=>$type, 'attr_value'=>$value));
				$product->copyAttr($itemidArray[$i], 'goaljerseys');
            }
			
            $this->view->showMsg('设置成功!');

        }else
        {

            $this->view->showMsg('设置有误!');

        }


    }
}
